package com.eschool.beans.converter;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.eschool.dao.ClassDao;
import com.eschool.model.Clas;
import com.eschool.util.ConstraintsUtil;


public class ClassConverter implements Converter {

    public static List<Clas> classDB;
    private static HttpSession session = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getSession();
    
   	public ClassConverter() {	
    			classDB = new ArrayList<Clas>();
    			// -- Adding the branch constraint before getting classes
    			classDB = ClassDao.getClasses(ConstraintsUtil.getConstraintsMap());
    }

    public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
        if (submittedValue.trim().equals("")) {
            return null;
        } else {
            try {
                for (Clas c : classDB) {
                    if (c.getClassTitle().equalsIgnoreCase(submittedValue)) {
                        return c;
                    }
                }
                
            } catch(NumberFormatException exception) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a Section"));
            }
        }

        return null;
    }

    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
        if (value == null || value.equals("")) {
            return "";
        } else {
            return ((Clas) value).getClassTitle();
        }
    }
}
